# -*- coding: utf-8 -*-
'''
###########################################
#  Created on 2011-12-5
#  @author: cl.lam
#  Description:
###########################################
'''
import traceback
from datetime import datetime as dt
from flask import session,g, app
from flask.helpers import url_for, flash
from werkzeug.utils import redirect
from flask.blueprints import Blueprint
from sqlalchemy.sql.expression import and_


from sys2do.util.decorator import templated, trycatch
from sys2do.util.common import _g,_error
from sys2do.model import DBSession,User,Group
from sys2do.constant import MESSAGE_ERROR, MSG_USER_NOT_EXIST,\
    MSG_WRONG_PASSWORD


from sys2do import login_manager
from flask_login import loginRequired, logout_user, login_user
from flask.globals import request

__all__ = ['bpAuth']

bpAuth = Blueprint('bpAuth', __name__)

index_url = lambda : url_for('bpRoot.view', action = "index")


@login_manager.user_loader
@trycatch()
def load_user(userid):
    return DBSession.query(User).filter(and_(User.active == 0 ,User.id == userid)).one()




@bpAuth.route("/logout")
@loginRequired
def logout():
    logout_user()
    return redirect(index_url())


@bpAuth.route("/login",methods = ['GET', 'POST'])
@templated('login.html')
def login():
    if request.method == "GET" : return {}
    
    try:
        u = DBSession.query(User).filter(and_(User.active == 0, User.name == _g('name'))).one()
    except:
        _error(traceback.print_exc())
        flash(MSG_USER_NOT_EXIST, MESSAGE_ERROR)
#        return redirect(url_for('bpAuth.login', next = _g('next')))
        return None
    else:
        if not _g('password'):
            flash(MSG_WRONG_PASSWORD, MESSAGE_ERROR)
#            return redirect(url_for('bpAuth.login', next = _g('next')))
            return None

        if not u.validatePassword(_g('password')):
            flash(MSG_WRONG_PASSWORD, MESSAGE_ERROR)
            return redirect(url_for('bpAuth.login', next = _g('next')))
            
            return None
        else:
            #fill the info into the session
            flag = login_user(u)
            if flag:            
                session['user_profile'] = {}
                permissions = set()
                for g in u.groups:
                    for p in g.permissions:
                        permissions.add(p.name)
                session['user_profile']['groups'] = [g.name for g in u.groups]
                session['user_profile']['permissions'] = list(permissions)
    
                u.last_login = dt.now()
                DBSession.commit()
                return redirect(index_url())
            else:
                flash("Error")
#                return redirect(url_for('bpAuth.login', next = _g('next')))
                return None
 
    return {}